package com.ukao.pad.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextClock;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.ukao.pad.HomeFragment;
import com.ukao.pad.R;
import com.ukao.pad.base.MvpActivity;
import com.ukao.pad.bean.StationBean;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.PrintHideDialogFragment;
import com.ukao.pad.dialog.QuitLoginDialogFragment;
import com.ukao.pad.eventbus.MainEvent;
import com.ukao.pad.presenter.HomePesenter;
import com.ukao.pad.utils.AppUtils;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.DensityUtils;
import com.ukao.pad.utils.ImageUtils;
import com.ukao.pad.view.HomeView;
import com.ukao.pad.widget.ShapedImageView;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends MvpActivity<HomePesenter>  implements HomeView {

    @BindView(R.id.wifi_name)
    TextView wifiName;
    @BindView(R.id.wifi)
    ImageView wifi;
    @BindView(R.id.left_control_menu_icon)
    ShapedImageView leftControlMenuIcon;
    @BindView(R.id.left_control_menu_username)
    TextView leftControlMenuUsername;
    @BindView(R.id.today)
    TextView today;
    @BindView(R.id.remove)
    StateImageView remove;
    @BindView(R.id.fame_layout)
    FrameLayout fameLayout;
    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.station_txt)
    TextView stationTxt;
    @BindView(R.id.left_control_menu_date)
    TextClock leftControlMenuDate;
    @BindView(R.id.left_control_menu_time)
    TextClock leftControlMenuTime;
    @BindView(R.id.left_control_menu_week)
    TextClock leftControlMenuWeek;
    private HomeFragment mHomeFragment;
    private WifiManager mWifiManager;
    private WifiReceiver mReceiver;
    private PrintHideDialogFragment mPrintHideDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        if (!CheckUtils.isMIUIDevices()){
            Beta.checkUpgrade(false,false);/*不提示正在检查更新，2不弹提示*/
        }
        initView();
    }


    @Override
    protected HomePesenter createPresenter() {
        return new HomePesenter(this);
    }

    @Override
    protected void initView() {
        mvpPresenter.stationTypesRequest();
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiName.setText(AppUtils.getWIfiName(this));
        ImageUtils.loadImage(this, SaveParamets.getHeadimgPath(this), leftControlMenuIcon, R.drawable.left_control_menu_icon);
        leftControlMenuUsername.setText(SaveParamets.getSaveUseName(this));
        mHomeFragment = new HomeFragment();
        //设置根Fragment布局
        loadRootFragment(R.id.fame_layout, mHomeFragment);

    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();


    }



    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @OnClick({R.id.today, R.id.left_control_menu_date, R.id.left_control_menu_icon, R.id.remove,R.id.wifi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_control_menu_icon:

                QuitLoginDialogFragment quitLoginDialog = new QuitLoginDialogFragment();
                quitLoginDialog.show(getSupportFragmentManager(),quitLoginDialog.getClass().getName());

                break;

            case R.id.today:


            case R.id.left_control_menu_date:

                break;
            case R.id.remove:
                int count = getSupportFragmentManager().getBackStackEntryCount();
                if (count > 1)
                    popTo(HomeFragment.class, false);
                break;
            case R.id.wifi:/*无线网*/

                HomeFragment mHomeFragment = findFragment(HomeFragment.class);
                if (mHomeFragment != null) {
                    mHomeFragment.startWifiFragment();
                }


                break;
        }
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(MainEvent event) {
        switch (event.getMessage()) {
            case login:
                startloginActivity();

                break;
            case quit:
                mvpPresenter.quitout();

                break;
            case print:
                Map mMap = (Map) event.getData();
                String deviceName = (String) mMap.get(ARG_PARAM1);
                String printMachine = (String) mMap.get(ARG_PARAM2);
                showPrinterDialog(deviceName, printMachine);
                break;
            case  station:
                stationTxt.setText(SaveParamets.getValname());

            break;
        }
    }

    /**
     * 打印机器
     */
    public void showPrinterDialog(String deviceName, String printMachine) {
        if (mPrintHideDialog==null){
            mPrintHideDialog=new PrintHideDialogFragment();

        }

        Bundle mBundle = new Bundle();
        mBundle.putString(ARG_PARAM1, deviceName);
        mBundle.putString(ARG_PARAM2, printMachine);
        mPrintHideDialog.setArguments(mBundle);
        mPrintHideDialog.show(getSupportFragmentManager(),mPrintHideDialog.getClass().getName());
    }

    @Override
    public void quitoutSuccess() {
        startloginActivity();
    }
    public void startloginActivity() {
        SaveParamets.setIsLogin(false);
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 注册wifi 广播
     */
    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
    }




    @Override
    public void loadStationSuccess(List<StationBean> StationBean) {
        if (!CheckUtils.isEmpty(StationBean)){
            for (StationBean stationBean : StationBean) {
                if (stationBean.isCheck()){
                    SaveParamets.setVal(stationBean.getVal());
                    SaveParamets.setValname(stationBean.getName());
                    stationTxt.setText(stationBean.getName());
                }
            }
        }
    }


    @Override
    public void onBackPressedSupport() {

        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        }
    }

    private class WifiReceiver extends BroadcastReceiver {
        protected static final String TAG = "ukao";

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                Log.d(TAG, "网络已经改变");
                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    Log.d(TAG, "wifi已经断开");
                    wifi.setImageResource(R.drawable.left_control_menu_no_wifi);
                    wifiName.setText("");
                } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                    Log.d(TAG, "正在连接...");
                    wifi.setImageResource(R.drawable.left_control_menu_no_wifi);
                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    Log.d(TAG, "连接到网络：" + wifiInfo.getBSSID());
                    wifi.setImageResource(R.drawable.left_control_menu_wifi);
                    String wifiId = wifiInfo != null ? wifiInfo.getSSID() : "";
                    wifiName.setText(wifiId);
                }

            }

        }
    }



}